package com.cfuture08.eweb4j.mvc.validator;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.cfuture08.eweb4j.mvc.ValidatorIF;
import com.cfuture08.eweb4j.mvc.config.bean.Field;
import com.cfuture08.eweb4j.mvc.config.bean.Validator;
import com.cfuture08.util.RegexList;
/**
 * 验证器帮助类
 * @author cfuture.aw
 *
 */
public class ValidatorHelper implements ValidatorIF {
	private String regex;

	public ValidatorHelper(String regex) {
		this.regex = regex;
	}

	@Override
	public Map<String, String> validate(Validator val,
			Map<String, String[]> map, HttpServletRequest request) {
		Map<String, String> valError = new HashMap<String, String>();
		for (Field f : val.getField()) {
			String[] value = map.get(f.getName());
			String v = value == null ? "" : value[0];
			if (!((String) v).matches(this.regex)) {
				valError.put(f.getName(), f.getMessage());
			}

			request.setAttribute(f.getName(), v);
		}
	
		return valError.isEmpty() ? null : valError;
	}

	public String getRegex() {
		return regex;
	}

	public void setRegex(String regex) {
		this.regex = regex;
	}

	public static void main(String[] args) {
		System.out.println("2005-04-04".matches(RegexList.date_regexp));
	}

}
